package one.stand.service.impl;

import cn.hutool.core.util.ObjectUtil;
import one.stand.mapper.SecurityAuthMapperExt;
import one.stand.model.SecurityAuth;
import one.stand.service.SecurityAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Service
public class SecurityAuthServiceImpl implements SecurityAuthService {

    @Autowired
    private SecurityAuthMapperExt securityAuthMapperExt;

    @Override
    public void save(SecurityAuth securityAuth) {
        if (Objects.isNull(securityAuth.getId())) {
            SecurityAuth securityAuthSelect = get(securityAuth.getType(), securityAuth.getTypeId(), securityAuth.getTypeAuth());
            securityAuth.setId(securityAuthSelect.getId());
        }

        if (Objects.nonNull(securityAuth.getId())) {
            SecurityAuth securityAuthUpdate = new SecurityAuth();
            securityAuthUpdate.setId(securityAuth.getId());
            securityAuthUpdate.setStartTime(ObjectUtil.defaultIfNull(securityAuth.getStartTime(), DEFAULT_START_TIME));
            securityAuthUpdate.setEndTime(ObjectUtil.defaultIfNull(securityAuth.getEndTime(), DEFAULT_END_TIME));
            securityAuthUpdate.setUpdateTime(new Date());
            securityAuthMapperExt.updateByPrimaryKeySelective(securityAuthUpdate);
        } else {
            if (Objects.isNull(securityAuth.getStartTime())) {
                securityAuth.setStartTime(DEFAULT_START_TIME);
            }
            if (Objects.isNull(securityAuth.getEndTime())) {
                securityAuth.setEndTime(DEFAULT_END_TIME);
            }
            securityAuth.setCreateTime(new Date());
            securityAuthMapperExt.insertSelective(securityAuth);
        }
    }

    @Override
    public List<SecurityAuth> getList(Integer type, Integer typeId) {
        return securityAuthMapperExt.selectList(type, typeId);
    }

    @Override
    public SecurityAuth get(Integer type, Integer typeId, Integer typeAuth) {
        SecurityAuth securityAuth = securityAuthMapperExt.select(type, typeId, typeAuth);
        if (Objects.isNull(securityAuth)) {
            securityAuth = new SecurityAuth();
            securityAuth.setStartTime(DEFAULT_START_TIME);
            securityAuth.setEndTime(DEFAULT_END_TIME);
        }
        return securityAuth;
    }
}
